/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.japo.java.matisse.samples;

import java.awt.Color;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author José A. Pacheco
 */
public class CajeroValidado extends javax.swing.JFrame {

    // Semáforos de validacion
    private boolean dineroOK;

    // Expresiones regulares
    private static final String ER_DINERO = "[0-9]+([,\\.][0-9]+)?";

    public CajeroValidado() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDinero = new javax.swing.JLabel();
        lblB20 = new javax.swing.JLabel();
        lblB50 = new javax.swing.JLabel();
        lblResto = new javax.swing.JLabel();
        txfDinero = new javax.swing.JTextField();
        lblTxtB20 = new javax.swing.JLabel();
        lblTxtB50 = new javax.swing.JLabel();
        lblTxtResto = new javax.swing.JLabel();
        btnDesglosar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cajero validado");
        setResizable(false);

        lblDinero.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblDinero.setText("Dinero");

        lblB20.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblB20.setText("Billetes 20");

        lblB50.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblB50.setText("Billetes 50");

        lblResto.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblResto.setText("Resto");

        txfDinero.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        txfDinero.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txfDinero.setText("0.00");
        txfDinero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txfDineroActionPerformed(evt);
            }
        });
        txfDinero.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txfDineroFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txfDineroFocusLost(evt);
            }
        });

        lblTxtB20.setBackground(java.awt.Color.white);
        lblTxtB20.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblTxtB20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblTxtB20.setText("0");
        lblTxtB20.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblTxtB20.setOpaque(true);

        lblTxtB50.setBackground(java.awt.Color.white);
        lblTxtB50.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblTxtB50.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblTxtB50.setText("0");
        lblTxtB50.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblTxtB50.setOpaque(true);

        lblTxtResto.setBackground(java.awt.Color.white);
        lblTxtResto.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        lblTxtResto.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblTxtResto.setText("0.00");
        lblTxtResto.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblTxtResto.setOpaque(true);

        btnDesglosar.setFont(new java.awt.Font("SansSerif", 0, 24)); // NOI18N
        btnDesglosar.setText("Desglosar");
        btnDesglosar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesglosarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lblDinero)
                            .addGap(18, 18, 18)
                            .addComponent(txfDinero, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lblB50)
                            .addGap(18, 18, 18)
                            .addComponent(lblTxtB50, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lblResto)
                            .addGap(18, 18, 18)
                            .addComponent(lblTxtResto, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(btnDesglosar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblB20)
                        .addGap(18, 18, 18)
                        .addComponent(lblTxtB20, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lblB20, lblDinero});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lblTxtB20, txfDinero});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lblB50, lblResto});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDinero)
                    .addComponent(txfDinero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblB50)
                    .addComponent(lblTxtB50))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblB20)
                    .addComponent(lblTxtB20))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblResto)
                    .addComponent(lblTxtResto))
                .addGap(18, 18, 18)
                .addComponent(btnDesglosar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnDesglosar, lblB20, lblB50, lblDinero, lblResto, lblTxtB20, lblTxtB50, lblTxtResto, txfDinero});

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txfDineroFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txfDineroFocusGained
        // Pone el color de fondo a CYAN
        txfDinero.setBackground(Color.CYAN);
    }//GEN-LAST:event_txfDineroFocusGained

    private void txfDineroFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txfDineroFocusLost
        try {
            // Validar campo de texto
            dineroOK = validarCampoTexto(txfDinero, ER_DINERO, "0.00");

            // Reformatear campo de texto de moneda
            reformatearCampoMonetario(txfDinero);
        } catch (NumberFormatException nfe) {
//            JOptionPane.showMessageDialog(this, "Hay un error en el valor introducido");
        } catch (PatternSyntaxException pse) {
            JOptionPane.showMessageDialog(this, "Hay un error en el patrón validador");
        } finally {
            // Poner en blanco el fondo del campo
            txfDinero.setBackground(Color.WHITE);
        }
    }//GEN-LAST:event_txfDineroFocusLost

    private void txfDineroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txfDineroActionPerformed
        // Pulsa el botón de desglosar
        btnDesglosar.doClick();
        
        // Enfoca el botón de desglosar - doClick no cambia el foco!!!!
//        btnDesglosar.requestFocus();        
    }//GEN-LAST:event_txfDineroActionPerformed

    private void btnDesglosarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDesglosarActionPerformed
        try {
            // Validar campos
            dineroOK = validarCampoTexto(txfDinero, ER_DINERO, "0.00");
            
            // Comprobar validez
            if (dineroOK) {
                desglosarDinero();
            } else {
                // Resetear los campos de resultado
                lblTxtB20.setText("0");
                lblTxtB50.setText("0");
                lblTxtResto.setText("0.00");
            }
        } catch (NumberFormatException e) {
            System.out.println(e);
        }
    }//GEN-LAST:event_btnDesglosarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CajeroValidado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CajeroValidado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CajeroValidado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CajeroValidado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CajeroValidado().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDesglosar;
    private javax.swing.JLabel lblB20;
    private javax.swing.JLabel lblB50;
    private javax.swing.JLabel lblDinero;
    private javax.swing.JLabel lblResto;
    private javax.swing.JLabel lblTxtB20;
    private javax.swing.JLabel lblTxtB50;
    private javax.swing.JLabel lblTxtResto;
    private javax.swing.JTextField txfDinero;
    // End of variables declaration//GEN-END:variables

    private void desglosarDinero() throws NumberFormatException {
        // Obtiene el valor del campo de texto
        String textoDinero = txfDinero.getText();

        // Obtiene el Locale utilizado
        Locale l = Locale.getDefault();
        if (textoDinero.indexOf('.') >= 0) {
            l = Locale.ENGLISH;
        }

        // Sustituye la coma por punto
        textoDinero = textoDinero.replace(',', '.');

        // Obtiene la cantidad de dinero
        double dinero = Double.parseDouble(textoDinero);

        // Recalcula el valor introducido
        textoDinero = String.format(l, "%.2f", dinero);

        // Reescribe el valor introducido
        txfDinero.setText(textoDinero);

        // Obtiene los billetes de 50
        int b50 = (int) (dinero / 50);
        lblTxtB50.setText(b50 + "");

        // Obtiene los billetes de 20
        int b20 = (int) ((dinero - b50 * 50) / 20);
        lblTxtB20.setText(b20 + "");

        // Obtiene la calderilla
        double resto = dinero - b50 * 50 - b20 * 20;

        // Obtiene el valor del resto
        String textoResto = String.format(l, "%.2f", resto);

        // Esribe el resto en el interfaz
        lblTxtResto.setText(textoResto);
    }

    private boolean validarCampoTexto(JTextField txfActual, String expReg, 
            String textoCampoVacio) throws PatternSyntaxException {
        // Semáforo de validación
        boolean validacionOK = false;

        // Obtiene el texto del campo
        String textoActual = txfActual.getText().trim();

        // Comprueba campo vacio
        if (textoActual.equals("")) {
            textoActual = textoCampoVacio;
        }

        // Restaura el texto formateado
        txfActual.setText(textoActual);

        // Patrón de la expresión regular
        Pattern patron = Pattern.compile(expReg);

        // Aplica el patrón al texto de prueba
        Matcher detector = patron.matcher(textoActual);

        // Comprueba la coincidencia
        if (detector.matches()) {
            // Contenido correcto
            txfActual.setForeground(Color.BLACK);

            // Actualiza el semáforo
            validacionOK = true;
        } else {
            // Contenido problemático
            txfActual.setForeground(Color.RED);
        }

        // Devuelve el resultado de la validacion
        return validacionOK;
    }

    private void reformatearCampoMonetario(JTextField txfDinero)
            throws NumberFormatException {
        // Obtiene el valor del campo de texto
        String textoDinero = txfDinero.getText();

        // Obtiene el locale por defecto
        Locale l = Locale.getDefault();

        // Sustituye la coma por punto
        if (textoDinero.indexOf(',') >= 0) {
            // Sustituye la coma
            textoDinero = textoDinero.replace(',', '.');
        } else {
            // Actualiza el locale
            l = Locale.ENGLISH;
        }

        // Obtiene la cantidad de dinero
        double dinero = Double.parseDouble(textoDinero);

        // Recalcula el valor introducido al locale
        textoDinero = String.format(l, "%.2f", dinero);

        // Reescribe el valor introducido
        txfDinero.setText(textoDinero);
    }
}
